package srv

import (
	"fmt"
	datasource2 "github.com/alibaba/sentinel-golang/ext/datasource"
	"github.com/alibaba/sentinel-golang/pkg/adapters/grpc"
	"github.com/alibaba/sentinel-golang/pkg/datasource/nacos"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	upbv1 "goTong/api/user/v1"
	"goTong/app/pkg/options"
	"goTong/gtong/core/trace"
	"goTong/gtong/server/rpcserver"
)

func NewNacosDataSource(opts *options.NacosOptions) (*nacos.NacosDataSource, error) {
	//从nacos中读取配置信息
	sc := []constant.ServerConfig{
		{
			IpAddr: opts.Host,
			Port:   opts.Port,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         opts.Namespace, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/sentinel/log",
		CacheDir:            "tmp/sentinel/cache",
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		return nil, err
	}
	//注冊流控规则
	h := datasource2.NewFlowRulesHandler(datasource2.FlowRuleJsonArrayParser)
	nds, err := nacos.NewNacosDataSource(configClient, opts.Group, opts.DataId, h)
	if err != nil {
		return nil, err
	}
	return nds, nil
}
func NewUserRPCServer(telemetry *options.TelemetryOptions,
	serverOptions *options.ServerOptions,
	dataNacos *nacos.NacosDataSource,
	userver upbv1.UserServer) (*rpcserver.Server, error) {

	//初始化open-telemetry的exporter
	trace.InitAgent(trace.Options{
		telemetry.Name,
		telemetry.Endpoint,
		telemetry.Sampler,
		telemetry.Batcher,
	})
	rpcAddr := fmt.Sprintf("%s:%d", serverOptions.Host, serverOptions.Port)

	var opts []rpcserver.ServerOption
	opts = append(opts, rpcserver.WithAddress(rpcAddr))
	if serverOptions.EnableLimit {
		opts = append(opts, rpcserver.WithUnaryInterceptor(grpc.NewUnaryServerInterceptor()))
		err := dataNacos.Initialize()
		if err != nil {
			return nil, err
		}
	}
	urpcServer := rpcserver.NewServer(opts...)

	upbv1.RegisterUserServer(urpcServer.Server, userver)

	return urpcServer, nil
}

//func NewUserRPCServer(cfg *config.Config) (*rpcserver.Server, error) {
//	//初始化open-telemetry的exporter
//	trace.InitAgent(trace.Options{
//		cfg.Telemetry.Name,
//		cfg.Telemetry.Endpoint,
//		cfg.Telemetry.Sampler,
//		cfg.Telemetry.Batcher,
//	})
//	//data := mock.NewUsers()
//	gormDB, err := db.GetDBFactoryOr(cfg.MySQLOptions)
//	if err != nil {
//		log.Fatal(err.Error())
//	}
//	data := db.NewUsers(gormDB)
//	srv := srv1.NewuserService(data)
//	userver := user.NewUserServer(srv)
//
//	rpcAddr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
//	urpcServer := rpcserver.NewServer(rpcserver.WithAddress(rpcAddr))
//	upbv1.RegisterUserServer(urpcServer.Server, userver)
//
//	return urpcServer, nil
//
//}
